package com.vip.zuul.ztools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * Description : 鉴权过滤器
 * @Author Evan Liu
 * @Date 2018年11月12日
 */
public class BlockUrlPreFilter extends ZuulFilter  {

    private static Logger log = LoggerFactory.getLogger(BlockUrlPreFilter.class);

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info("Request Method:{};URL:{}",request.getMethod(),request.getRequestURL().toString());
        
        Object accessToken = request.getParameter("accessToken");
        if(accessToken == null) {
            log.warn("access token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            JSONObject response = new JSONObject();
            response.put("success", false);
            response.put("code", 401);
            response.put("messages", "TOKEN FAIL");
            ctx.setResponseBody(JSON.toJSONString(response));
            return null;
        }
        log.info("access token ok");
        return null;
    }

}
